import { Component, OnInit } from '@angular/core';
import {Path} from "../../../../portal/admin/admin-breadcrumb/breadcrumb";
import {PageSubject} from "../../../../util/page-subject";
import {PollutantSourceService} from "./pollutant-source.service";
import {OneDialogService} from "../../../../widgets/one-dialog/one-dialog.service";
import {ResponseUtil} from "../../../../util/response-util";
import {MsgResult} from "../../../../models/msg-result";
import {MsgConstants} from "../../../../constants/constants";

declare var $;
declare var echarts;
declare var moment;

@Component({
  selector: 'app-pollutant-source',
  templateUrl: './pollutant-source.component.html',
  styleUrls: ['./pollutant-source.component.css']
})
export class PollutantSourceComponent implements OnInit {
  config;echartDataObj;
  constructor(
    private pageSubject : PageSubject,
    private PollutantSourceService : PollutantSourceService,
    private responseUtil :ResponseUtil,
    private dialogService: OneDialogService,
  ) { }

  ngOnInit() {
    $(".one-data-loadState").show();
    this.pushPage();
    this.siteButtonData();
  }
  //面包屑导航
  pushPage() {
    let path = new Path("数据研判", "");
    this.pageSubject.pushPage("污染源历史曲线", "", path);
  }

  //表格数据
  siteButtonData(){
    this.PollutantSourceService.getUserSiteData().subscribe(
      result => this.responseUtil.success(result,this.siteButtonDataResult),
      message => this.responseUtil.error(message)
    );
  }
  private siteButtonDataResult = (result: MsgResult) =>{
    if (result && result.code == MsgConstants.MSG_CODE_OK) {
      this.siteButtonDataDataTree(result.data);
    }
    if (result && result.code != MsgConstants.MSG_CODE_OK) {
      this.dialogService.info(result.message);
    }
  }

  //站点按钮
  siteButtonDataDataTree(data){
    let siteHtml = " ";
    let localSite = [
      {"name":"raiseDustSite","chinese":"扬尘"},
      {"name":"industrySite","chinese":"工业废气"},
      {"name":"waterPollutionSite","chinese":"工业废水"},
      {"name":"lampblackSite","chinese":"油烟"},
      {"name":"sprayBoothSite","chinese":"喷漆房"},
    ]
    $.each(localSite,function (j,siteList) {
      $.each(data,function (i,list) {
        if(list==siteList.name){
          siteHtml+='<div class="btn btn-default" data-type="'+siteList.name+'">'+siteList.chinese+'</div>';
        }
      });
    });
    if(siteHtml){
      $(".user_site_button").html(siteHtml);
      $(".user_site_button").find(".btn:first").addClass("active");
      this.initTime();
      this.initBtnStyle();
      this.listNationSiteData();
      this.initBtnEvent();
    }else{
      $(".one-content").html("暂无数据");
    }


  };

  //按钮样式
  initBtnStyle() {
    $("a").click(function(e){
      e.preventDefault();
    });
    //改变input样式
    $('input').iCheck({
      checkboxClass: 'icheckbox_minimal-green',
      radioClass: 'iradio_minimal-green',
      increaseArea: '20%' // optional
    });
    $("#pollutantSourceChart").css({"width":"100%","height":$(window.innerHeight)[0]-330+"px"});
    //按钮点击事件
    $(".btn-group .btn").click(function(){
      $(this).addClass("active").siblings(".active").removeClass("active");
    });

    //点击站点列表
    $(".one-inline-btn").click(function(){
      $(this).find(".dropdown-menu").show();
    }).mouseleave(function(){
      $(this).find(".dropdown-menu").hide();
    });
    //点击站点列表中的删除图标
    $(".one-inline-container").on("click",".btn>.glyphicon-remove",function(){
      $(this).parent().remove();
      if($(".one-inline-container>.btn").length<5){
        $('.list-inline input').iCheck('enable');
      }else{
        $('.list-inline .icheckbox_minimal-green:not(.checked) input').iCheck('disable');
      }
      var btnId = $(this).parent().attr("id");
      $(".dropdown-menu label").each(function(){
        var  id = $(this).find("input").attr("id");
        if( btnId == id){
          $(this).find("input").iCheck('uncheck');
        }
      });
    });
  }

  //初始化日期插件
  initTime(){
    this.config = {
      timePicker:true,
      timePickerIncrement:5,
      timePicker24Hour:true,
      parentEl:$(".wrapper"),
      maxDate:new Date(),
      locale:{
        format:"YYYY-MM-DD HH:00",
        separator: " 至 ",
        applyLabel : '确定',
        cancelLabel : '取消',
        fromLabel: '从',
        toLabel: '到',
        weekLabel: 'W',
        customRangeLabel: 'Custom Range',
        daysOfWeek:["日","一","二","三","四","五","六"],
        monthNames: ["一月","二月","三月","四月","五月","六月","七月","八月","九月","十月","十一月","十二月"],
        firstDay:1
      },
      startDate:moment().subtract(1,"d").subtract(1,"h").format("YYYY-MM-DD HH")+":00",
      endDate: moment().subtract(1,"h").format("YYYY-MM-DD HH")+":00"
    };
    $("#pollutantSourceDate").daterangepicker(this.config);
  }

  //点击事件
initBtnEvent(){
  //点击站点类型
  $(".dropdown-menu>.one-btn-data-type").on("click",".btn",function(){
    var id = $(this).data("type");
    console.log(id)
    $("#"+id).show().siblings("ul").hide();
  });

  //查询站点
  $("#searchPollute").bind("input propertychange",function () {
    let searchSiteVal = $("#searchPollute").val();
  if(searchSiteVal){
    $(".dropdown-menu label").each(function(){
      var text = $(this).text();
      if(text.indexOf(searchSiteVal)!=-1){
        $(this).parent().show();
      }else{
        $(this).parent().hide();
      }
    })
  }else{
    $(".dropdown-menu label").parent().show();
  }
  })

  //阻止查询enter冒泡
  $("#searchPollute").keydown(function(e){
    if(e.keyCode == "13"){
      e.preventDefault();
    }
  }).change(function(e){
    e.preventDefault();
  });

  //点击选择日期
  $(".oneDay").click(function(){
    this.config.locale.format="YYYY-MM-DD HH:00";
    this.config.startDate =moment().subtract(2,"d").subtract(1,"h").format("YYYY-MM-DD HH")+":00";
    this.config.endDate = moment().subtract(1,"d").subtract(1,"h").format("YYYY-MM-DD HH")+":00";
    $("#pollutantSourceDate").daterangepicker(this.config);
    $("#dayData").hide().removeClass("active");
    $("#hourData").show().addClass("active");
  }.bind(this));
  $(".weekDay").click(function(){
    if($(".dataType").find(".active").attr("id") == "dayData"){
      this.config.locale.format="YYYY-MM-DD";
      this.config.startDate = moment().subtract(1,"w").subtract(1,"d").format("YYYY-MM-DD");
      this.config.endDate = moment().subtract(1,"d").format("YYYY-MM-DD");
      $("#pollutantSourceDate").daterangepicker(this.config);
    }else{
      this.config.locale.format="YYYY-MM-DD HH:00";
      this.config.startDate = moment().subtract(1,"w").subtract(1,"d").subtract(1,"h").format("YYYY-MM-DD HH")+":00";
      this.config.endDate = moment().subtract(1,"d").subtract(1,"h").format("YYYY-MM-DD HH")+":00";
      $("#pollutantSourceDate").daterangepicker(this.config);
    }
    $("#dayData").show();
    $("#hourData").show();
  }.bind(this));
  $(".monthDay").click(function(){
    if($(".dataType").find(".active").attr("id") == "dayData"){
      this.config.locale.format="YYYY-MM-DD";
      this.config.startDate = moment().subtract(1,"M").subtract(1,"d").format("YYYY-MM-DD");
      this.config.endDate = moment().subtract(1,"d").format("YYYY-MM-DD");
      $("#pollutantSourceDate").daterangepicker(this.config);
    }else{
      this.config.locale.format="YYYY-MM-DD HH:00";
      this.config.startDate = moment().subtract(1,"M").subtract(1,"d").subtract(1,"h").format("YYYY-MM-DD HH")+":00";
      this.config.endDate = moment().subtract(1,"d").subtract(1,"h").format("YYYY-MM-DD HH")+":00";
      $("#pollutantSourceDate").daterangepicker(this.config);
    }
    $("#hourData").show();
    $("#dayData").show();
  }.bind(this));
  $(".yearDay").click(function(){
    this.config.locale.format="YYYY-MM-DD";
    this.config.startDate = moment().subtract(1,"y").subtract(1,"d").format("YYYY-MM-DD");
    this.config.endDate = moment().subtract(1,"d").format("YYYY-MM-DD");
    $("#pollutantSourceDate").daterangepicker(this.config);
    $("#hourData").hide().removeClass("active");
    $("#dayData").show().addClass("active");
  }.bind(this));
  $(".hour").click(function(){
    let startTime;
    let timeBtn = $(".timeBtn").find(".active").attr("id");
    if(timeBtn=="oneDay"){
      startTime = moment().subtract(2,"d").subtract(1,"h").format("YYYY-MM-DD HH")+":00";
    }else if(timeBtn=="weekDay"){
      startTime = moment().subtract(1,"w").subtract(1,"d").subtract(1,"h").format("YYYY-MM-DD HH")+":00";
    }else if(timeBtn=="monthDay"){
      startTime = moment().subtract(1,"m").subtract(1,"d").subtract(1,"h").format("YYYY-MM-DD HH")+":00";
    }
    this.config.locale.format="YYYY-MM-DD HH:00";
    this.config.startDate =startTime;
    this.config.endDate =  moment().subtract(1,"d").subtract(1,"h").format("YYYY-MM-DD HH")+":00";
    $("#pollutantSourceDate").daterangepicker(this.config);
  }.bind(this));
  $(".day").click(function(){
    let startTime;
    let timeBtn = $(".timeBtn").find(".active").attr("id");
    if(timeBtn=="oneDay"){
      startTime = moment().subtract(2,"d").format("YYYY-MM-DD");
    }else if(timeBtn=="weekDay"){
      startTime = moment().subtract(1,"w").subtract(1,"d").format("YYYY-MM-DD");
    }else if(timeBtn=="monthDay"){
      startTime = moment().subtract(1,"M").subtract(1,"d").format("YYYY-MM-DD");
    }
    this.config.locale.format="YYYY-MM-DD";
    this.config.startDate = startTime;
    this.config.endDate = moment().subtract(1,"d").format("YYYY-MM-DD");
    $("#pollutantSourceDate").daterangepicker(this.config);
  }.bind(this));
  $(".search").click(function () {
    $(".one-data-loadState").show();
    this.chartData();
  }.bind(this));

}

  //污染源历史站点下拉数据
  listNationSiteData(){
    this.PollutantSourceService.getPollutantSiteData().subscribe(
      result => this.responseUtil.success(result,this.getPollutantSiteDataResult),
      message => this.responseUtil.error(message)
    );
  }
  private getPollutantSiteDataResult = (result: MsgResult) =>{
    if (result && result.code == MsgConstants.MSG_CODE_OK) {
      this.getPollutantSiteDataTree(result.data);
    }
    if (result && result.code != MsgConstants.MSG_CODE_OK) {
      this.dialogService.info(result.message);
    }
  }
  private getPollutantSiteDataTree(data){
    if(data == null){
      $("#compareChart").html("<div class='one-message-null'>暂无数据</div>");
    }else{
      console.log("省控站数据加载成功");
      $(".one-data-loadState").hide();
      this.dropDownData(data);
      this.chartData();
    }
  }

  //请求下拉列表中的数据
  dropDownData(dropDatas) {
  var dropIndustryHtml = "",dropRaiseDustHtml = "",dropLampblackHtml = "",dropSprayBoothHtml = "",waterPollutionHtml = "",waterSurfaceHtml = "";
  $.each(dropDatas, function (index, dropData) {
    var type = dropData.siteTypeCode;
    if(type == "101"){
      dropIndustryHtml += '<li><label><input type="radio" name="siteName" id='+dropData.siteCode+'>' + dropData.siteName + '</label></li>';
    }else if(type == "102"){
      dropRaiseDustHtml += '<li><label><input type="radio" name="siteName" id='+dropData.siteCode+'>' + dropData.siteName + '</label></li>';
    }else if(type == "103"){
      dropLampblackHtml += '<li><label><input type="radio" name="siteName" id='+dropData.siteCode+'>' + dropData.siteName + '</label></li>';
    }else if(type == "104"){
      dropSprayBoothHtml += '<li><label><input type="radio" name="siteName" id='+dropData.siteCode+'>' + dropData.siteName + '</label></li>';
    }else if(type == "201"){
      waterPollutionHtml += '<li><label><input type="radio" name="siteName" id='+dropData.siteCode+'>' + dropData.siteName + '</label></li>';
    }else if(type == "006" || type == "007" || type == "008" || type == "009" || type == "010" || type == "011"){
      waterSurfaceHtml += '<li><label><input type="radio" name="siteName" id='+dropData.siteCode+'>' + dropData.siteName + '</label></li>';
    }
  });
  dropIndustryHtml == ""? $("#industrySite").html("暂无数据12"):$("#industrySite").html(dropIndustryHtml);
  dropRaiseDustHtml == ""?$("#raiseDustSite").html("暂无数据1"):$("#raiseDustSite").html(dropRaiseDustHtml);
  dropLampblackHtml == ""?$("#lampblackSite").html("暂无数据12"):$("#lampblackSite").html(dropLampblackHtml);
  dropSprayBoothHtml == ""?$("#sprayBoothSite").html("暂无数据1"):$("#sprayBoothSite").html(dropSprayBoothHtml);
  waterPollutionHtml == ""?$("#waterPollutionSite").html("暂无数据12"):$("#waterPollutionSite").html(waterPollutionHtml);
  waterSurfaceHtml == ""?$("#waterSurfaceSite").html("暂无数据1"):$("#waterSurfaceSite").html(waterSurfaceHtml);
  //改变input样式
  $('input').iCheck({
    checkboxClass: 'icheckbox_minimal-green',
    radioClass: 'iradio_minimal-green',
    increaseArea: '20%' // optional
  });
  //初始化站点选择
    var firstShow =$(".user_site_button").find(".active").attr("data-type");
    $("#"+firstShow).show();
  var initCheckRadio = $("#"+firstShow+" li:first-child");
  initCheckRadio.find("input").iCheck('check');
  var btnText1 = initCheckRadio.find("label").text();
  var btnId = initCheckRadio.find("input").attr("id");
  var btnPoint = firstShow;
  var initBtnHtml = '<div class="btn btn-success" id='+btnId+' data-point='+btnPoint+'>'+btnText1+' <i class="glyphicon glyphicon-remove"></i></div>';
  $(".one-inline-container").html(initBtnHtml);
  //点击下拉列表中的元素
  $('.list-inline input').on('ifChecked', function(e){
    var text = $(this).parent().parent().text();
    var id = $(this).attr("id");
    var btnPoint = $(this).parent().parent().parent().parent().attr("id");
    var btnHtml = '<div class="btn btn-success" id='+id+' data-point=' +btnPoint+ '>'+text+' <i class="glyphicon glyphicon-remove"></i></div>';
    $(".one-inline-container").append(btnHtml);
  }).on('ifUnchecked', function(e){
    var text = $.trim($(this).parent().parent().text());
    $(".one-inline-container>.btn").each(function(){
      var btnText = $.trim($(this).text());
      if(btnText==text){
        $(this).remove();
      }
    });
  });
}

  //图表数据处理
  chartData(){
    let pointCode = $(".one-inline-container>.btn").attr("id");
    let pointType = $(".one-inline-container>.btn").data("point");
    let rangeTime = $("#pollutantSourceDate").val();
    let dataType = $(".dataType").find(".active").attr("id");
    let startTime;let endTime;
    if(dataType=="hourData"){
      startTime = $.trim(rangeTime.split("至")[0])+":00";
      endTime = $.trim(rangeTime.split("至")[1])+":00";
    }else{
      startTime = $.trim(rangeTime.split("至")[0])+" 00:00:00";
      endTime = $.trim(rangeTime.split("至")[1])+" 00:00:00";
    }

    this.echartDataObj = {"dataType":dataType,"pointCode":pointCode,"pointType":pointType,"startTime":startTime,"endTime":endTime}
    this.getPollutantSourceData(this.echartDataObj);
    }

  //图表数据
  getPollutantSourceData(obj){
    this.PollutantSourceService.getPollutantSourceData(obj).subscribe(
      result => this.responseUtil.success(result,this.getPollutantSourceResult),
      message => this.responseUtil.error(message)
    );
  }
  private getPollutantSourceResult = (result: MsgResult) =>{
    if (result && result.code == MsgConstants.MSG_CODE_OK) {
      this.ggetPollutantSourceResultTree(result.data);
    }
    if (result && result.code != MsgConstants.MSG_CODE_OK) {
      this.dialogService.info(result.message);
    }
  }
  private ggetPollutantSourceResultTree(data){
    $(".one-data-loadState").hide();
    if(data == [] || data == null){
      //$(".dropdown-menu .list-inline").html("暂无数据");
      $("#pollutantSourceChart").html("<div class='one-message-null'>暂无数据</div>");
    }else{
      console.log("图表数据加载成功");
      this.chartRender(data);
    }
  }

  //    图表
chartRender(chartList){
  var pollutantSourceChart = echarts.init(document.getElementById('pollutantSourceChart'));
  //图表配置信息
  var option = {
    tooltip: {
      trigger: 'axis'
    },
    legend: {
      data:chartList.pollutionFactor
    },
    xAxis: {
      type: 'category',
      nameGap:"20",
      name: "日期",
      nameLocation:"start",
      boundaryGap: false,
      data: chartList.time
    },
    yAxis: {
      name: "指数",
      type: 'value'
    },
    series: []
  };
  //series中的内容
  $.each(chartList.pollutionFactor,function(index,nameList){
    // var  seriesList = {};
    // seriesList.type = "line";
    // seriesList.smooth = true;
    // seriesList.name = nameList;
    // seriesList.data = chartList.dataList[index];
    option.series.push({"type":"line","smooth":true,"name":nameList,"data":chartList.dataList[index]})
  });
  pollutantSourceChart.setOption(option);
}
}
